package Controller;

import java.awt.Color;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import Model.ListTableModel;
import View.LoginWindow;

public class DBLink {
	
	public Connection connect;
	public String user;
	public String password;
	public String hostname;
    public String databasename;
    public String port;
	public boolean stat;
	public JLabel lbl;
	public LoginWindow login;
	
	public DBLink(JLabel label,LoginWindow l){
		this.connect = null;
		this.user = "Atendente";
		this.password = "123654";
		//this.password = "";
		this.hostname = "146.164.4.16";
		this.databasename = "Agencia Aerea";
		this.port = "5432";
		lbl = label;
		loadDriver();
		connect();
	}
	
	public boolean checkLogin(){
		if(login != null){
			boolean t1 = (user.equals(login.textField.getText()));
			boolean t2 = (hostname.equals(login.host.getText()));
			boolean t3 = (databasename.equals(login.database.getText()));
			//return t1;
			System.out.println("DBLink: " + t1 +"<>" + t2+"<>" + t3);
			return (t1 || t2 || t3);
		}
		else return true;
		//return true;
	}
	
	public boolean connect(){
		stat = tryConnect();
		if(stat){lbl.setText("Online "); lbl.setForeground(Color.BLUE);}
		else {lbl.setText("Offline "); lbl.setForeground(Color.RED);}
		return stat;
	}
	
	@Override
	public DBLink clone(){
		return this;
	}
	
	public ListTableModel runSQL(String sql){
		
		Statement stmt = null;
		
		try {
			
			stmt = connect.createStatement();
	        ResultSet rs = stmt.executeQuery(sql);
	        
	        
			ListTableModel model = ListTableModel.createModelFromResultSet( rs);

			return model;
			
			} catch (Exception e1) {JOptionPane.showMessageDialog(null, e1.toString(), "DBLink - Error", JOptionPane.ERROR_MESSAGE); return null;} 
	}
	
	public boolean runSQLcmd(String sql){
		Statement stmt = null;
		
		try {
			
			stmt = connect.createStatement();
			boolean rs = stmt.execute(sql);
	        //ResultSet rs = stmt.executeQuery(sql);
	        return true;
	        
			//ListTableModel model = ListTableModel.createModelFromResultSet( rs);
			
			} catch (Exception e1) {JOptionPane.showMessageDialog(null, e1.toString(), "DBLink - Error", JOptionPane.ERROR_MESSAGE); return false;}
	}
	
	public boolean tryConnect(){
		//System.out.println("DBLink: Tentando Conectar no DB");
		if(connect == null){
			if(checkLogin()){
				//this.updateLogin();
				try {
					//String stm = "jdbc:oracle:thin:@";
					String stm = "jdbc:postgresql://";
					stm += this.hostname + ":";
					stm += this.port + "/";
					stm += this.databasename;
					//connect = DriverManager.getConnection("jdbc:oracle:thin:@SERVER01:1521:TABUAS", this.user,this.password);
					System.out.println("Address: " + stm);
					connect = DriverManager.getConnection(stm, this.user,this.password);
					if(connect == null){
						System.out.println("DBLink: Deu ruim na conexao");
						return false;
					}
					else{
						System.out.println("DBLink: Fiz Conexao direito");
						return true;
					}
				
				} catch (SQLException e) {
					JOptionPane.showMessageDialog(null, e.toString(), "DBLink Error", JOptionPane.ERROR_MESSAGE);
					return false;
				}
			}
			else{
				System.out.println("DBLink: Nao Fiz Conexao Antes, nao tentarei");
				return false;
			}
		}
		else{
			if(checkLogin()){
				System.out.println("DBLink: Mudou o usuario!");
				//Nao precisa chamar o updateLogin pq a chamada recursiva vai fazer isso!!!!!!
				try {
					connect.close();
					System.out.println("DBLink: Fechei Conexao");
					if(connect.isClosed()){
						System.out.println("DBLink: connect is closed()");
						connect = null;
						return tryConnect();
					}
					else{
						System.out.println("DBLink: connect is closed() deu ruim");
						return false;
					}
					
				} catch (SQLException e) {
					JOptionPane.showMessageDialog(null, e.toString(), "DBLink Error", JOptionPane.ERROR_MESSAGE);
					return false;
				}
				
			}
			else{
				System.out.println("DBLink: Conexao Inalterado!");
				return true;
			}
		}
	}
	
	public void closeAll(){
		if(connect != null){
			try {
				connect.close();
				if(connect.isClosed()){
					System.out.println("DBLink: Fechei Conexao");
				}
			} catch (SQLException e) {
				JOptionPane.showMessageDialog(null, e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
			}
			connect = null;
		}
		else{
			System.out.println("DBLink: Ja era null");
		}
	}
	
	public boolean loadDriver()
	{
		System.out.println("DBLink: Tentando Load Driver");
		try {
			 
			//Class.forName("oracle.jdbc.driver.OracleDriver");
			Class.forName("org.postgresql.Driver");
			
			System.out.println("DBLink: PostgreSQL JDBC Driver Registered!");
			return true;
 
		} catch (ClassNotFoundException e) {
 
			JOptionPane.showMessageDialog(null, e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
	}
}
